package com.ruoyi.mall.ware.service.impl;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.ruoyi.common.core.constant.WareConstant;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.mall.ware.domain.PurchaseDetail;
import com.ruoyi.mall.ware.mapper.PurchaseDetailMapper;
import com.ruoyi.mall.ware.service.IPurchaseDetailService;
import com.ruoyi.mall.ware.service.IWareSkuService;
import com.ruoyi.mall.ware.vo.MergeVo;
import com.ruoyi.mall.ware.vo.PurchaseDoneVo;
import com.ruoyi.mall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.mall.ware.mapper.PurchaseMapper;
import com.ruoyi.mall.ware.domain.Purchase;
import com.ruoyi.mall.ware.service.IPurchaseService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 采购信息Service业务层处理
 *
 * @author zhangqishu
 * @date 2022-06-14
 */
@Service
public class PurchaseServiceImpl implements IPurchaseService {
    @Autowired
    private PurchaseMapper purchaseMapper;

    @Autowired
    private IPurchaseDetailService purchaseDetailService;

    @Autowired
    private IWareSkuService wareSkuService;

    /**
     * 查询采购信息
     *
     * @param id 采购信息主键
     * @return 采购信息
     */
    @Override
    public Purchase selectPurchaseById(Long id) {
        return purchaseMapper.selectPurchaseById(id);
    }

    /**
     * 查询采购信息列表
     *
     * @param purchase 采购信息
     * @return 采购信息
     */
    @Override
    public List<Purchase> selectPurchaseList(Purchase purchase) {
        return purchaseMapper.selectPurchaseList(purchase);
    }

    /**
     * 新增采购信息
     *
     * @param purchase 采购信息
     * @return 结果
     */
    @Override
    public int insertPurchase(Purchase purchase) {
        purchase.setCreateTime(DateUtils.getNowDate());
        return purchaseMapper.insertPurchase(purchase);
    }

    /**
     * 修改采购信息
     *
     * @param purchase 采购信息
     * @return 结果
     */
    @Override
    public int updatePurchase(Purchase purchase) {
        purchase.setUpdateTime(DateUtils.getNowDate());
        return purchaseMapper.updatePurchase(purchase);
    }

    /**
     * 批量删除采购信息
     *
     * @param ids 需要删除的采购信息主键
     * @return 结果
     */
    @Override
    public int deletePurchaseByIds(Long[] ids) {
        return purchaseMapper.deletePurchaseByIds(ids);
    }

    /**
     * 删除采购信息信息
     *
     * @param id 采购信息主键
     * @return 结果
     */
    @Override
    public int deletePurchaseById(Long id) {
        return purchaseMapper.deletePurchaseById(id);
    }

    /**
     * 查询未领取的采购单
     *
     * @param purchase
     * @return
     */
    @Override
    public List<Purchase> unReceiveList(Purchase purchase) {
        //状态信息 未新建的
        QueryWrapper<Purchase> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0).or().eq("status", 1);

        return purchaseMapper.selectList(wrapper);

    }

    /**
     * 合并采购单
     *
     * @param mergeVo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int mergePurchase(MergeVo mergeVo) {

        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId == null) {
            //1. 新建一个采购单
            Purchase purchase = new Purchase();
            purchase.setCreateTime(new Date());
            purchase.setUpdateTime(new Date());
            purchase.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseMapper.insert(purchase);
            purchaseId = purchase.getId();
        }
        //合并采购单
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetail> collect = items.stream().map(i -> {
            PurchaseDetail purchaseDetail = new PurchaseDetail();
            purchaseDetail.setId(i);
            purchaseDetail.setPurchaseId(finalPurchaseId);
            purchaseDetail.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetail;
        }).collect(Collectors.toList());

        boolean b = purchaseDetailService.updateBatchById(collect);

        Purchase purchase = new Purchase();
        purchase.setId(purchaseId);
        purchase.setUpdateTime(new Date());
        purchaseMapper.updatePurchase(purchase);
        return b ? 1 : 0;
    }

    /**
     * 领取采购单
     *
     * @param ids 采购单id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int receivedPurchase(List<Long> ids) {
        //1.确认当前采购单状态是新建或者已分配状态
        List<Purchase> list = ids.stream()
                .map(i -> purchaseMapper.selectById(i))
                .filter(j -> j.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || j.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
                .peek(z -> {
                    z.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    z.setUpdateTime(new Date());
                })
                .collect(Collectors.toList());

        //2.改变采购单的状态
        this.updateBatchById(list);

        //TODO 确认采购单状态0，1才可以合并

        //3.改变采购项的状态
        list.forEach(item -> {
            List<PurchaseDetail> purchaseDetailList = purchaseDetailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetail> collect = purchaseDetailList.stream().map(purchaseDetail -> {
                PurchaseDetail purchaseDetail1 = new PurchaseDetail();
                purchaseDetail1.setId(purchaseDetail.getId());
                purchaseDetail1.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetail1;

            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect);

        });


        return 0;
    }

    /**
     * 完成采购单
     *
     * @param purchaseDoneVo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int donePurchase(PurchaseDoneVo purchaseDoneVo) {
        //1. 改变采购单状态
        Long id = purchaseDoneVo.getId();

        //2.改变采购项状态
        Boolean flag = true;
        List<PurchaseItemDoneVo> purchaseItemDoneVoList = purchaseDoneVo.getPurchaseItemDoneVoList();
        List<PurchaseDetail> updates = new ArrayList<>();
        for (PurchaseItemDoneVo purchaseItemDoneVo : purchaseItemDoneVoList) {
            PurchaseDetail detail = new PurchaseDetail();
            if (purchaseItemDoneVo.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                flag = false;
                detail.setStatus(purchaseItemDoneVo.getStatus());
            } else {
                //3.将成功单采购进行入库
                PurchaseDetail purchaseDetail = purchaseDetailService.getById(purchaseItemDoneVo.getItemId());
                wareSkuService.addStock(purchaseDetail.getSkuId(), purchaseDetail.getWareId(), purchaseDetail.getSkuNum());
                detail.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
            }
            //
            detail.setId(purchaseItemDoneVo.getItemId());

            updates.add(detail);
        }

        purchaseDetailService.updateBatchById(updates);

        //改变采购单状态
        Purchase purchase = new Purchase();
        purchase.setId(id);
        purchase.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode() : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchase.setUpdateTime(new Date());
        boolean b = this.updateById(purchase);


        return b ? 1 : 0;
    }

    @Override
    public boolean saveBatch(Collection<Purchase> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean saveOrUpdateBatch(Collection<Purchase> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean updateBatchById(Collection<Purchase> entityList, int batchSize) {
        return false;
    }

    @Override
    public boolean saveOrUpdate(Purchase entity) {
        return false;
    }

    @Override
    public Purchase getOne(Wrapper<Purchase> queryWrapper, boolean throwEx) {
        return null;
    }

    @Override
    public Map<String, Object> getMap(Wrapper<Purchase> queryWrapper) {
        return null;
    }

    @Override
    public <V> V getObj(Wrapper<Purchase> queryWrapper, Function<? super Object, V> mapper) {
        return null;
    }

    @Override
    public BaseMapper<Purchase> getBaseMapper() {
        return null;
    }
}
